package com.lzh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lzh.pojo.entity.TgNotice;
import com.lzh.pojo.resp.BaseResp;
import com.lzh.pojo.resp.NoticeResp;
import com.lzh.service.NoticeService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Li
 * @ 2022/3/29
 */
@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    RestHighLevelClient restHighLevelClient ;

    @Override
    public BaseResp find(Map map) {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("tg_notice") ;
        searchRequest.types("doc") ;
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//      分页
//        int start = (noticeResp.getPage()-1)*noticeResp.getSize() ;
//        searchSourceBuilder.from(start) ;
//        searchSourceBuilder.size(noticeResp.getSize()) ;

        Object noticeContent1 = map.get("noticeContent");
        String noticeContent_ = null ;
        if (noticeContent1 != null){
            noticeContent_ = noticeContent1.toString();
        }
        if (StringUtils.isEmpty(noticeContent_)){
            searchSourceBuilder.query(QueryBuilders.matchAllQuery()) ;
        }else{
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(noticeContent_, "noticeName","noticeContent").field("noticeName",10)) ;
        }


        //设置高亮的字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("courserName");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(searchSourceBuilder) ;
        List<TgNotice> list = new ArrayList<>() ;
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest);
            SearchHits hits = search.getHits();
            BaseResp baseResp = new BaseResp();

            baseResp.setTotal(hits.getTotalHits());

            SearchHit[] hits1 = hits.getHits();

            for (SearchHit hit : hits1) {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null){
                    HighlightField noticeName = highlightFields.get("noticeName");
                    HighlightField noticeContent = highlightFields.get("noticeContent");
                    if (noticeName!=null){
                        Text[] fragments = noticeName.getFragments();
                        StringBuffer stringBuffer = new StringBuffer();
                        if (fragments!=null&&fragments.length>0){
                            for (Text text:fragments
                            ) {
                                stringBuffer.append(text);
                            }
                            hit.getSourceAsMap().put("noticeName",stringBuffer.toString());
                        }
                    }
                    if (noticeContent!=null){
                        Text[] fragments = noticeContent.getFragments();
                        StringBuffer stringBuffer = new StringBuffer();
                        if (fragments!=null&&fragments.length>0){
                            for (Text text:fragments
                            ) {
                                stringBuffer.append(text);
                            }
                            hit.getSourceAsMap().put("noticeContent",stringBuffer.toString());
                        }
                    }
                }

                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                String s = JSONObject.toJSONString(sourceAsMap);
                TgNotice tgNotice = JSONObject.parseObject(s, TgNotice.class);
                list.add(tgNotice) ;
            }
            baseResp.setData(list) ;
            baseResp.setCode(1);
            baseResp.setMsg("查询成功") ;
            return baseResp ;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResp(0 , "查询失败"  , null , null ) ;
    }

    @Override
    public BaseResp findByName(String id) {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("tg_notice") ;
        searchRequest.types("doc") ;
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termsQuery("_id",id)) ;

        searchRequest.source(searchSourceBuilder) ;
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest);
            SearchHits hits = search.getHits();
            SearchHit[] hits1 = hits.getHits();
            BaseResp baseResp = new BaseResp();
            for (SearchHit hit : hits1) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();

                String s = JSONObject.toJSONString(sourceAsMap);
                TgNotice tgNotice = JSONObject.parseObject(s, TgNotice.class);

                if (tgNotice != null){
                    baseResp.setData(tgNotice) ;
                    baseResp.setCode(1);
                    baseResp.setMsg("查询成功") ;
                    return baseResp ;
                }

            }
            baseResp.setCode(1);
            baseResp.setMsg("暂无该数据") ;
            return baseResp ;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResp(0 , "查询失败" , null , null) ;

    }
}
